<?php
	include("config.php");
	session_start();
// 	if(!isset($_SESSION['user_id']))
// 		header('location:index.php');
	if(!isset($_SESSION['username']))
		return 0;

	if(isset($_GET['op']))
	{
		$languageId = 32;
		$results = array();
		if(!isset($client))
		{
			$options = array('languageId'=>$languageId,'trace' => 1,'login' => 'autohit2','password' => 'bont39er','encoding' => 'ISO-8859-1','trace' => true,'exceptions' => true);
			$client = new SoapClient('http://autohit.web-catalogue.eu/main/service/vehicle.wsdl',$options);
		}
		
		$pathinfo = pathinfo($_SERVER['PHP_SELF']);
		
		switch($_GET['op'])
		{
			case 1: //model series
				$_SESSION['model_series'] = array();
				
				// Engine code
				if( (isset($_GET['engineId'])) && (!empty($_GET['engineId'])))
					$parameters_models = array(
						'languageId' => $languageId,
						'manufacturerId' => $_GET['manufacturer_id'],
						'engineId' => $_GET['engineId'],
						'pc' => 1,
						'cv' => 0,
						'modelFilter' => 1
					);
				else
					$parameters_models = array(
						'languageId' => $languageId,
						'manufacturerId' => $_GET['manufacturer_id'],
						'pc' => 1,
						'cv' => 0,
						'modelFilter' => 1
					);

				$result_models = $client->searchVehicleModelSeries($parameters_models);
				if(count($result_models))
				{
					if(!is_array($result_models->modelSeries))
						$result_models->modelSeries = array($result_models->modelSeries);
					$output = '<option value="0">- Моля изберете сериен модел -</option>';
					$arrModel = array();
					foreach($result_models->modelSeries as $key=>$data)
					{
						$id = trim($data->id);
						$name = trim($data->name);
						
						if($id && $name!=''){
							if(isset($data->manufacturedFrom))
								$manufacturedFrom = trim($data->manufacturedFrom);
							else
								$manufacturedFrom = '';
								
							if(isset($data->manufacturedTo))
								$manufacturedTo = trim($data->manufacturedTo);
							else
								$manufacturedTo = '';
								
							$results[$key]['id'] = $id;
							$results[$key]['name'] = $name.' ('.$manufacturedFrom.' - '.$manufacturedTo.')';

							if(($_GET['model_id'])==$id)
								$selected = 'selected';
							else
								$selected = '';

							$output.= '<option value="'.$id.'" '.$selected.'>'.$name.' ('.$manufacturedFrom.' - '.$manufacturedTo.')'.'</option>';
						}
						
						$arrModel[$id] = $name;
					}
					
					$_SESSION['model_series'] = $arrModel;
//					echo json_encode($results);

					echo $output;
				}
				break;
			case 2:
				// Model
				$_SESSION['fuel_type'] = array();
				$_SESSION['vehicle'] = array();

				if($_GET['model_id'])
				{
				//function to sort
					function aasort (&$array, $key)
					{
						$sorter = array();
						$ret = array();
						reset($array);
						foreach($array as $ii => $va) {
							$va = (array) $va;
							$sorter[$ii] = $va[$key];
						}
						asort($sorter);
						foreach($sorter as $ii => $va) {
							$va = (array) $va;
							$ret[$ii] = $array[$ii];
						}
						$array = $ret;
					}
					// Engine code
					if( (isset($_GET['engineId'])) && (!empty($_GET['engineId'])))
						$parameters_show = array('modelId'=>$_GET['model_id'], 'encoding' => 'ISO-8859-1' , 'engineId'=>$_GET['engineId'], 'fuelId' => -1, 'ccm' => -1, 'modelFilter'=>1);
					else
						$parameters_show = array('modelId'=>$_GET['model_id'], 'encoding' => 'ISO-8859-1' , 'fuelId' => -1, 'ccm' => -1, 'modelFilter'=>1);

					$result_show_en = $client->searchVehicle($parameters_show);
					$result_show = $client->searchVehicle(array_merge($parameters_show, array('languageId'=>$languageId)));

					// Check is empty object
					if( (count( (array)$result_show) ) != 0)
					{
						foreach($result_show->fuelOut as $key => $data)
						{
							if(is_numeric($key))
								$fuel_type[$data->id] = $data->name;
							else
								$fuel_type[$result_show->fuelOut->id] = $result_show->fuelOut->name;
						}

						$_SESSION['fuel_type'] = $result_show->fuelOut;
					
						$pathinfo = pathinfo($_SERVER['PHP_SELF']);
						if( isset($_SERVER['HTTPS'] )  && $_SERVER['HTTPS'] != 'off' ) 
							$redirect_path = 'https://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
						else
							$redirect_path = 'http://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
						if(isset($_SESSION['engine_code']) && ($_SESSION['engine_code']) )
							$location = "parent.window.location.href='index.php?manufacturerId=".$_GET['manufacturer_id']."&engineId=". $_SESSION['engine_id']."&engine_code=". urlencode($_SESSION['engine_code'])."'";
						else
						{
							$location = 'ajaxManufacturerLoadModels(1,'.$_GET['manufacturer_id'].')';
							$_SESSION['engine_id'] = 0;
						}
						if($result_show)
						{
							if(!is_array($result_show_en->vehicle))
								$result_show_en->vehicle = array($result_show_en->vehicle);
						
							$output = '<meta http-equiv="content-type" content="text/html; charset=Windows-1251" />
									<script type="text/javascript" src="fancybox/lib/jquery-1.10.1.min.js"></script>
									<script type="text/javascript" src="fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
									<script type="text/javascript" src="fancybox/source/jquery.fancybox.js?v=2.1.5"></script>

									<link rel="stylesheet" type="text/css" href="fancybox/source/jquery.fancybox.css?v=2.1.5" media="screen" />

									<link rel="stylesheet" type="text/css" href="fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" />
									<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>

									<link rel="stylesheet" type="text/css" href="fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" />
									<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>

									<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.6"></script>
									<script type="text/javascript">
										function iframeInfoBox(id, manufacturer_id, model_id){
											$.fancybox.open({
													href : "iframe.php?id="+id+"&manufacturer_id="+manufacturer_id+"&model_id="+model_id,
													type : "iframe",
													padding : 5
												});
										}
									</script>
									<script type="text/javascript" src="js/scripts.js"></script>
									<link rel="stylesheet" type="text/css" href="css/styles.css" />
									<div style="float:left; width: 100%; margin-bottom: 5px; font-size: 14px; font-weight: bold;">
										<div id="leki_avtomobili" style="float: left; width: 123px; height: 15px;" onClick=\'parent.window.location.href = "index.php";\' onmouseover=\'this.style.cursor="pointer";\' onmouseout=\'this.style.cursor="normal";\'"></div>
										<div style="float: left;">&nbsp;>>&nbsp;</div>
										<div style="float: left;" class="steplink" onClick="'.$location.'">'.$_SESSION['manufacturers'][$_GET['manufacturer_id']].'</div>
										<div style="float: left;">&nbsp;>>&nbsp;</div>
										<div style="float: left;">'.$_SESSION['model_series'][$_GET['model_id']].'</div>
									</div>
									<div style="clear: both;"></div>
									<table class="hovertable" width="100%" style="border-collapse: collapse; font-size: 14px;" cellspacing="10">
										<tr style="background: none repeat scroll 0 0 #B6B6B6; color: #ffffff;">
											<th height="30"><b>'.mb_convert_encoding('Описание','Windows-1251','UTF-8').'</b></th>
											<th height="30"><b>'.mb_convert_encoding('Код на мотора','Windows-1251','UTF-8').'</b></th>
											<th height="30"><b>'.mb_convert_encoding('Година','Windows-1251','UTF-8').'</b></th>
											<th height="30"><b>'.mb_convert_encoding('Двигател (KW/HP)','Windows-1251','UTF-8').'</b></th>
											<th height="30"><b>'.mb_convert_encoding('Гориво','Windows-1251','UTF-8').'</b></th>
											<th height="30"><b>'.mb_convert_encoding('Куб.см','Windows-1251','UTF-8').'</b></th>
											<th height="30"><b>'.mb_convert_encoding('Тип','Windows-1251','UTF-8').'</b></th>
										</tr>';

							if(!is_array($result_show->vehicle))
								$result_show->vehicle = array($result_show->vehicle);
							$i = 0;
							aasort( $result_show->vehicle, 'ccm');
							foreach($result_show->vehicle as $key => $data)
							{
								$data->name = $result_show_en->vehicle[$key]->name;
								$_SESSION['vehicle'][$data->id] = $data;
								$i++;

								//$bgcolor = ( ($i % 2 ==0) ? "#ffffff" : "#eeeeee");
								$bgcolor = "#ffffff";

								if(substr($data->manufacturedTo,0,4))
									$checkVehicleYear = substr($data->manufacturedFrom,0,4).'-'.substr($data->manufacturedTo,0,4);
								else
									$checkVehicleYear = substr($data->manufacturedFrom,0,4);

								$name =  '';
								$count = 0;
								$exp = explode(' ', $data->name);

								// Ако името на модела има ПРАЗНО МЯСТО
								$pos_space = strrpos($_SESSION['manufacturers'][$_GET['manufacturer_id']], " ");
								if(!empty($pos_space)){
									$explode_model = explode(' ', $_SESSION['manufacturers'][$_GET['manufacturer_id']]);
									$_SESSION['manufacturers'][$_GET['manufacturer_id']] = $explode_model[0];
								}

								if($exp[0] == $_SESSION['manufacturers'][$_GET['manufacturer_id']])
									$count ++;
								$exp_models = explode(' ', $_SESSION['model_series'][$_GET['model_id']]);
								$count += count($exp_models);
								if($exp[$count] == end($exp_models))
									$count ++;
								$count_label = count ($exp);
								if($count < $count_label)
								{
									for($j = $count; $j < $count_label; $j++)
									{
										$name = $name.' '.$exp[$j];
									}
								}
								else
								  $name = $data->name;

								//$output .= '<tr><td>'.$data->name.'</td></tr>';

								$output .= "<tr bgcolor=".$bgcolor.">";

								$output .= "<td height='15' class='table_style_list' onmouseover=\"this.style.cursor='pointer';\" onmouseout=\"this.style.cursor='normal';\">
										<img src='images/info.gif' onClick='iframeInfoBox(".$data->id.", ".$_GET['manufacturer_id'].", ".$_GET['model_id'].");' alt='' style='float: left; margin-right: 10px;' />
										<a class='link' style='float: left;' onclick=\"ajaxLoadHistory(".$_GET['manufacturer_id'].", ".$_GET['model_id'].", ".$data->id.");\">".$name."</a>
									    </td>";

								if(!isset($data->engines))
									$data->engines = array();

								if(!is_array($data->engines))
									$data->engines = array($data->engines);
								
								$engines = array();
								foreach($data->engines as $k=>$v){
									if(isset($v->description))
									      $engines[$v->description] = $v->description;
								}
											
								//$output .= (isset($data->engines) && isset($data->engines->description)) ? "<td height='30' style='text-align: center;'><a style='color: #000000; text-decoration: none;' onclick=\"ajaxLoadHistory(".$_GET['manufacturer_id'].", ".$_GET['model_id'].", ".$data->id.");\">".$data->engines->description."</a></td>" : "<td>&nbsp;</td>";
								$output .= (count($engines)>0) ? "<td height='15' class='table_style_list'><a class='link' onclick=\"ajaxLoadHistory(".$_GET['manufacturer_id'].", ".$_GET['model_id'].", ".$data->id.");\">".implode(", ", $engines)."</a></td>" : "<td height='15' class='table_style_list'>&nbsp;</td>";
								
								$output .= "<td height='15' class='table_style_list'>
										<a class='link' onclick=\"ajaxLoadHistory( ".$_GET['manufacturer_id'].", ".$_GET['model_id'].", ".$data->id.");\">".$checkVehicleYear."</a>
									    </td>";

								$output .= "<td height='15' class='table_style_list'>
										<a class='link' onclick=\"ajaxLoadHistory(".$_GET['manufacturer_id'].", ".$_GET['model_id'].", ".$data->id.");\" >".$data->kw.' / '.$data->hp."</a>
									    </td>";

								$output .= "<td height='15' class='table_style_list'>
										<a class='link' onclick=\"ajaxLoadHistory(".$_GET['manufacturer_id'].", ".$_GET['model_id'].", ".$data->id.");\">".$fuel_type[$data->fuelType]."</a>
									    </td>";
								
								$output .= "<td height='15' class='table_style_list'>
										<a class='link' onclick=\"ajaxLoadHistory(".$_GET['manufacturer_id'].", ".$_GET['model_id'].", ".$data->id.");\">".$data->ccm."</a>
									    </td>";

								$output .= "<td height='15' class='table_style_list'>
										<a class='link' onclick=\"ajaxLoadHistory(".$_GET['manufacturer_id'].", ".$_GET['model_id'].", ".$data->id.");\" >".$data->bodyTypeName."</a>
									    </td>";
								$output .= '</tr>';
							}
							$output .= '</table>';
						}

						echo $output;
					}
					else
						echo $output = '<meta http-equiv="content-type" content="text/html; charset=Windows-1251" />
								<link rel="stylesheet" type="text/css" href="css/styles.css" />
								<table class="hovertable" width="100%" style="border-collapse: collapse; font-size: 14px;" cellspacing="10">
									<tr style="background: none repeat scroll 0 0 #B6B6B6; color: #ffffff;">
										<th height="30"><b>'.mb_convert_encoding('Описание','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Код на мотора','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Година','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Двигател (KW/HP)','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Гориво','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Куб.см','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Тип','Windows-1251','UTF-8').'</b></th>
									</tr>
									<tr>
										<td height="30" colspan="7"><div class="no_result">'.mb_convert_encoding('Няма намерени резултати','Windows-1251','UTF-8').'</div></td>
									</tr>';
				}
				else
					echo $output = '<meta http-equiv="content-type" content="text/html; charset=Windows-1251" />
								<link rel="stylesheet" type="text/css" href="css/styles.css" />
								<table class="hovertable" width="100%" style="border-collapse: collapse; font-size: 14px;" cellspacing="10">
									<tr style="background: none repeat scroll 0 0 #B6B6B6; color: #ffffff;">
										<th height="30"><b>'.mb_convert_encoding('Описание','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Код на мотора','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Година','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Двигател (KW/HP)','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Гориво','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Куб.см','Windows-1251','UTF-8').'</b></th>
										<th height="30"><b>'.mb_convert_encoding('Тип','Windows-1251','UTF-8').'</b></th>
									</tr>
									<tr>
										<td height="30" colspan="7"><div class="no_result">'.mb_convert_encoding('Няма намерени резултати','Windows-1251','UTF-8').'</div></td>
									</tr>';
				break;
			
				case 3:
					// Engine Code
					if(!empty($_GET['engine_code']))
					{
// 						$_SESSION['engine_code'] = $_GET['engine_code'];
						
						//manufacturers engine
						$parameters_engine = array('manufacturerId'=>-1, 'filterText'=>urldecode(trim($_GET['engine_code'])));
						$result_engine =  $client->searchEngine($parameters_engine);

						if(count( (array)$result_engine))
						{
							$output = '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
									<a href="index.php">
										<div id="leki_avtomobili" style="float: left; width: 123px; height: 15px; margin-bottom:5px;" onmouseover=\'this.style.cursor="pointer";\' onmouseout=\'this.style.cursor="normal";\'></div>
									</a>
									<table class="hovertable" width="100%" style="border-collapse: collapse; font-size: 14px;" cellspacing="10">
										<tr style="background: none repeat scroll 0 0 #B6B6B6; color: #ffffff;">
											<th height="30"><b>Производител</b></th>
											<th height="30"><b>Описание</b></th>
											<th height="30"><b>Двигател KW (от-до)</b></th>
											<th height="30"><b>Двигател HP (от-до)</b></th>
										</tr>';
							
							$flag = 0;
							$i = 0;
							
							if(!is_array($result_engine->engine))
								$result_engine->engine = array($result_engine->engine);


							foreach($result_engine->engine as $key => $data)
							{
								$_SESSION['vehicle'][$data->id] = $data;
								if($data->id)
									$flag = 1;
							
								$i++;
								//$bgcolor = ( ($i % 2 ==0) ? "#ffffff" : "#eeeeee");
								$bgcolor = "#ffffff";

								$output .= "<tr bgcolor=".$bgcolor.">";


								$output .= "<td class='table_style_list' style='text-align: left;' height='15'><a class='link' onclick=\"parent.window.location.href='index.php?manufacturerId=".$data->manufacturerId."&engineId=".$data->id."&engine_code=".urlencode($data->description)."'\">".mb_convert_encoding($data->manufacturerName,'Windows-1251','UTF-8')."</a></td>";
								$output .= "<td class='table_style_list' height='15'><a class='link' onclick=\"parent.window.location.href='index.php?manufacturerId=".$data->manufacturerId."&engineId=".$data->id."&engine_code=".urlencode($data->description)."'\">".$data->description."</a></td>";
								
								if($data->kwTo)
									$kw = $data->kwFrom.' - '.$data->kwTo;
								else
									$kw = $data->kwFrom;

								if($data->hpTo)
									$hp = $data->hpFrom.' - '.$data->hpTo;
								else
									$hp = $data->hpFrom;
								
								$output .= "<td class='table_style_list' height='15'><a class='link' onclick=\"parent.window.location.href='index.php?manufacturerId=".$data->manufacturerId."&engineId=".$data->id."&engine_code=".urlencode($data->description)."'\">".$kw."</a></td>";
								$output .= "<td class='table_style_list' height='15'><a class='link' onclick=\"parent.window.location.href='index.php?manufacturerId=".$data->manufacturerId."&engineId=".$data->id."&engine_code=".urlencode($data->description)."'\">".$hp."</a></td>";
								$output .= "</tr>";
							}
							
							$output.= '</table>';
							
							if(empty($flag))
								$output = '<div id="main_car_manufacturer">
										<a href="index.php">
										      <div id="leki_avtomobili" style="float: left; width: 123px; height: 15px; margin-bottom:5px;" onmouseover=\'this.style.cursor="pointer";\' onmouseout=\'this.style.cursor="normal";\'></div>
										</a>
										<div id="manufacturer_all" style="float: left; width: 100%; display: none;">
										      <div class="car_manufacturer" style="float: left;">Лек автомобил</div>
										</div>
									   </div><br/>
									   <div class="no_result">Няма намерени резултати</div>';
						}
						else
							$output = '<div id="main_car_manufacturer">
									<a href="index.php">
										<div id="leki_avtomobili" style="float: left; width: 123px; height: 15px; margin-bottom:5px;" onmouseover=\'this.style.cursor="pointer";\' onmouseout=\'this.style.cursor="normal";\'></div>
									</a>
									<div id="manufacturer_all" style="float: left; width: 100%; display: none;">
										<div class="car_manufacturer" style="float: left;">Лек автомобил</div>
									</div>
								   </div><br/>
								   <div class="no_result">Няма намерени резултати</div>';
							
						echo $output;
					}
				
				break;
				case 4:
					$_SESSION['label'] = '';
					if( ($_GET['manufacturer_id']) && ($_GET['model_id']) && ($_GET['product_id']) && (isset($_SESSION['model_series'])) )
					{
						if($_SESSION['vehicle'][$_GET['product_id']]->manufacturedTo)
							$checkVehicleYear = substr($_SESSION['vehicle'][$_GET['product_id']]->manufacturedFrom,0,4).'-'.substr($_SESSION['vehicle'][$_GET['product_id']]->manufacturedTo,0,4);
						else
							$checkVehicleYear = substr($_SESSION['vehicle'][$_GET['product_id']]->manufacturedFrom,0,4);
							
						$_SESSION['label'] = mb_convert_encoding($_SESSION['vehicle'][$_GET['product_id']]->name.' '.$checkVehicleYear, 'Windows-1251', 'UTF-8');

// 						$user_id = $_SESSION['user_id'];
						$username = $_SESSION['username'];
						$manufacturer_id = (int)$_GET['manufacturer_id'];
						$labelManufacturer = urldecode($_GET['textmanufacturer']);
						
						if(!is_array($_SESSION['model_series']))
							$model_series = array($_GET['model_id']=>$_SESSION['model_series']);
						else
							$model_series = $_SESSION['model_series'];
							
						$labelModel = mysql_real_escape_string($model_series[$_GET['model_id']]);
						$model_seria_id = (int)$_GET['model_id'];
						$product_group_id = (int)$_GET['product_id'];
						$created = strtotime("now");
						
						$engine_code = isset($_SESSION['engine_code']) ? $_SESSION['engine_code'] : '';
						$engine_id = isset($_SESSION['engine_id']) ? $_SESSION['engine_id'] : 0;
						
						//$explode = explode(' ', $_SESSION['label']);
						//$explode[0] = $labelManufacturer;
						//$explode[1] = $labelModel;
						
						//$label = implode(' ',$explode);
						$label = mb_convert_encoding($_SESSION['vehicle'][$_GET['product_id']]->name.' '.$checkVehicleYear, 'Windows-1251', 'UTF-8');
						$label = mysql_real_escape_string($label);
/*
						$query = sprintf("INSERT INTO `users_history` (`user_id`, `labelManufacturer`, `labelModel`, `manufacturer_id`, `model_seria_id`, `product_group_id`, `created`, `label`)
										  VALUES (%d, '%s', '%s', %d, %d, %d, %d, '%s')", $user_id, $labelManufacturer, $labelModel, $manufacturer_id, $model_seria_id, $product_group_id, $created, $label);
*/
						$query = sprintf("
							INSERT INTO `users_history`
								(`username`, `labelManufacturer`, `labelModel`, `manufacturer_id`, `model_seria_id`, `product_group_id`, `created`, `label`, `engine_id`, `engine_code`)
							VALUES ('%s', '%s', '%s', %d, %d, %d, %d, '%s', %d, '%s')", $username, $labelManufacturer, $labelModel, $manufacturer_id, $model_seria_id, $product_group_id, $created, $label, $engine_id, $engine_code);
						$result = mysql_query($query) or die(mysql_error());
						
						if($result){
// 							$rez = mysql_query("SELECT * FROM `users_history` WHERE `user_id` = ".$user_id." ORDER BY `created` DESC LIMIT 0,10");
							$rez = mysql_query("SELECT * FROM `users_history` WHERE `username` = '".$username."' ORDER BY `created` DESC LIMIT 0,10");
							$numRows = mysql_num_rows($rez);
						
							$results = array();
							if($numRows){
								$output = '?id='.$_GET['product_id'].'&manufacturer_id='.$_GET['manufacturer_id'].'&model_id='.$_GET['model_id'].'||<option value="0">- История на автомобили -</option>';
							
								while($fetch = mysql_fetch_assoc($rez)){
									$output.= '<option value="'.$fetch['user_history_id'].'_'.$fetch['manufacturer_id'].'_'.$fetch['model_seria_id'].'_'.$fetch['product_group_id'].'">'.$fetch['label'].'</option>';
								}
							}
						}
						else
							$output = 'manufacturer_id='.$_GET['manufacturer_id'].'&model_id='.$_GET['model_id'].'&product_id='.$_GET['product_id'].'||<option value="0">- История на автомобили -</option>';
						
						echo $output;
					}
					else
						echo 0;
				
				break;
				case 5:
					unset($_SESSION['model_series']);
					$_SESSION['tree'] = array();
					$_SESSION['flag_tree'] = array();
					$_SESSION['label'] = '';
					$explode = explode("_", $_GET['id']);

					// Table - users_history
					$query = sprintf("SELECT `label`, `engine_code`, `engine_id`, `model_seria_id`, `labelModel` FROM `users_history` WHERE `user_history_id` = %d LIMIT 0,1", $explode[0]);
					$rez = mysql_query($query);
					$numRows = mysql_num_rows($rez);

					if($numRows){
						$fetch = mysql_fetch_assoc($rez);
						$_SESSION['label'] = $fetch['label'];
						$_SESSION['engine_code'] = $fetch['engine_code'];
						$_SESSION['engine_id'] = $fetch['engine_id'];
						$_SESSION['model_series'][$fetch['model_seria_id']] = $fetch['labelModel'];
					}

					// ---------------- Vehicle -------------------

					//function to sort
					function aasort (&$array, $key)
					{
						$sorter = array();
						$ret = array();
						reset($array);
						foreach($array as $ii => $va) {
							$va = (array) $va;
							$sorter[$ii] = $va[$key];
						}
						asort($sorter);
						foreach($sorter as $ii => $va) {
							$va = (array) $va;
							$ret[$ii] = $array[$ii];
						}
						$array = $ret;
					}

					$_SESSION['fuel_type'] = array();
					$_SESSION['vehicle'] = array();

					$parameters_show = array('modelId'=>$explode[2], 'encoding' => 'ISO-8859-1' , 'fuelId' => -1, 'ccm' => -1, 'modelFilter'=>1);
					$result_show_en = $client->searchVehicle($parameters_show);
					$result_show = $client->searchVehicle(array_merge($parameters_show, array('languageId'=>$languageId)));

					// Check is empty object
					if( (count( (array)$result_show) ) != 0)
					{
						if(!is_array($result_show->vehicle))
							$result_show->vehicle = array($result_show->vehicle);
							
						if(!is_array($result_show_en->vehicle))
							$result_show_en->vehicle = array($result_show_en->vehicle);

						aasort( $result_show->vehicle, 'ccm');
						foreach($result_show->vehicle as $key => $data) {
							$data->name = $result_show_en->vehicle[$key]->name;
							$_SESSION['vehicle'][$data->id] = $data;
						}

						foreach($result_show->fuelOut as $key => $data)
						{
							if(is_numeric($key))
								$fuel_type[$data->id] = $data->name;
							else
								$fuel_type[$result_show->fuelOut->id] = $result_show->fuelOut->name;
						}

						$_SESSION['fuel_type'] = $result_show->fuelOut;
					}

					echo json_encode($explode);
				break;
/*				case 6:
					if( ($_GET['manufacturer_id']) && ($_GET['product_id']) && (isset($_SESSION['engine_code'])) )
					{
// 						$user_id = $_SESSION['user_id'];
						$username = $_SESSION['username'];
						$manufacturer_id = (int)$_GET['manufacturer_id'];
						$product_group_id = (int)$_GET['product_id'];
						$engine_code = mysql_real_escape_string($_SESSION['engine_code']);
						$created = strtotime("now");
						$label = urlencode($_SESSION['label']);

// 						$query = sprintf("INSERT INTO `users_history` (`user_id`, `manufacturer_id`, `product_group_id`, `engine_code`, `created`, `label`)
// 										  VALUES (%d, %d, %d, '%s', %d, '%s')", $user_id, $manufacturer_id, $product_group_id, $engine_code, $created, $label);

						$query = sprintf("
							INSERT INTO `users_history` (`usename`, `manufacturer_id`, `product_group_id`, `engine_code`, `created`, `label`)
							VALUES ('%s', %d, %d, '%s', %d, '%s')", $username, $manufacturer_id, $product_group_id, $engine_code, $created, $label);
						$result = mysql_query($query) or die(mysql_error());
						
						if($result){
// 							$rez = mysql_query("SELECT * FROM `users_history` WHERE `user_id` = ".$user_id." ORDER BY `created` DESC LIMIT 0,10");
							$rez = mysql_query("SELECT * FROM `users_history` WHERE `username` = '".$username."' ORDER BY `created` DESC LIMIT 0,10");
							$numRows = mysql_num_rows($rez);
						
							$results = array();
							if($numRows){
								while($fetch = mysql_fetch_assoc($rez)){
									$results[$fetch['user_history_id']] = $fetch;
								}
							}
							
							echo json_encode($results);
						}
						else
							echo 0;
					}
					else
						echo 0;
				break; */
				case 7:
					if($_GET['manufacturer_id'])
					{
						$parameters_models = array('languageId'=>$languageId,'manufacturerId'=>$_GET['manufacturer_id'],'pc'=>1,'cv'=>0,'modelFilter'=>1);
						$result_models = $client->searchVehicleModelSeries($parameters_models);

						// Manufactured YEAR
						$arrYearManufactured = array();
						$arrayModelSeries = array();

						if(!is_array($result_models->modelSeries))
							$result_models->modelSeries = array($result_models->modelSeries);
						foreach($result_models->modelSeries as $key=>$data)
						{
							$manufacturedFrom = explode(".", $data->manufacturedFrom);

							if(substr($manufacturedFrom[1], 0,1)==0)
								$manufacturedYearFrom = '20'.$manufacturedFrom[1];
							else
								$manufacturedYearFrom = '19'.$manufacturedFrom[1];

							$arrYearManufactured[$manufacturedYearFrom] = $manufacturedFrom[1];

							if(isset($data->manufacturedTo)){
								$manufacturedTo = explode(".", $data->manufacturedTo);

								if(substr($manufacturedTo[1], 0,1)==0)
									$manufacturedYearTo = '20'.$manufacturedTo[1];
								else
									$manufacturedYearTo = '19'.$manufacturedTo[1];

								$arrYearManufactured[$manufacturedYearTo] = $manufacturedTo[1];
							}

							$id = trim($data->id);
							$name = trim($data->name);
							if($id && $name!='')
							{
								if(isset($data->manufacturedFrom))
									$manufacturedFrom = trim($data->manufacturedFrom);
								else
									$manufacturedFrom = '';

								if(isset($data->manufacturedTo))
									$manufacturedTo = trim($data->manufacturedTo);
								else
									$manufacturedTo = '';

								if($manufacturedTo)
									$manufacturedFromTo = $manufacturedFrom.' - '.$manufacturedTo;
								else
									$manufacturedFromTo = $manufacturedFrom;

								$arrayModelSeries[$id] = '<div class="car_manufacturer_left" id="table_manufacturer['.$id.']">
												<a onmouseover="mouseOver(this);" onmouseout="mouseOut(this);" onClick="this.style.color=\'#ff0000\'; ajaxShowResults(2, '.$_GET['manufacturer_id'].','.$id.', 0);">
													<span style="font-weight: bold;">'.$name.'</span>
												</a>
												<div style="float: right;"><b>'.$manufacturedFromTo.'</b></div>
											  </div>';
							}
						}

						// Count
						if(count(array_filter($arrayModelSeries))>0)
						{
							if( isset($_SERVER['HTTPS'] )  && $_SERVER['HTTPS'] != 'off' ) 
							    $redirect_path = 'https://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
							else
							    $redirect_path = 'http://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);

							$output = '<meta http-equiv="content-type" content="text/html; charset=Windows-1251" />
								   <link rel="stylesheet" type="text/css" href="css/styles.css" />
								   <div style="float:left; width: 100%; margin-bottom: 5px; font-size: 14px; font-weight: bold;">
									  <div id="leki_avtomobili" style="float: left; width: 123px; height: 15px;" onClick=\'window.location.href = "'.$redirect_path.'";\' onmouseover=\'this.style.cursor="pointer";\' onmouseout=\'this.style.cursor="normal";\'"></div>
									  <div style="float: left;">&nbsp;>>&nbsp;</div>
									  <div style="float: left;">'.$_SESSION['manufacturers'][$_GET['manufacturer_id']].'</div>
								   </div>';

							if(count($arrYearManufactured)>0)
							{
								ksort($arrYearManufactured);

								$output.= '<div style="margin-top: 5px; font-size: 13px; font-weight: bold;">
										<img src="images/godina_na_proizvodstvo.png" alt="" height="16" />
									   </div>
									   <div style="float: left; width: 100%; margin-top: 5px; margin-bottom: 10px; font-size: 13px;">';

								foreach($arrYearManufactured as $year=>$label_year){
									$output.='<a style="float: left; margin-right: 5px; text-decoration: underline;" onmouseover="mouseOver(this);" onmouseout="mouseOut(this);" onClick="ajaxManufacturerYearLoadModels(8,'.$_GET['manufacturer_id'].', '.$label_year.');">'.$year.'</a>';
								}

								$output.= '</div>';
							}


							$output.= '<div class="car_manufacturer" style="float: left;">
									<div class="car_manufacturer_left">
										<div style="float: left;"><img src="images/modelna_poredica.png" alt="" /></div>
										<div style="float: right;"><img src="images/bql_godina_na_proizvodstvo.png" alt="" /></div>
									</div>
									<div class="car_manufacturer_right">
										<div style="float: left;"><img src="images/modelna_poredica.png" alt="" /></div>
										<div style="float: right;"><img src="images/bql_godina_na_proizvodstvo.png" alt="" /></div>
									</div>
								   </div>';

							$count = 2;
							$arrOut = array_chunk($arrayModelSeries, ceil(count($arrayModelSeries)/$count));
							array_unshift($arrOut, null);
							$arrOut = call_user_func_array("array_map", $arrOut);

							foreach ($arrOut as $br => $row){
								if(is_array($row))
								{
									foreach($row as $index => $name){
										$output.= mb_convert_encoding($name,'Windows-1251','UTF-8');
									}
								}
								else
									$output.= mb_convert_encoding($row, 'Windows-1251','UTF-8');
							}
						}
						else
							$output.= '<div class="no_result"><img src="images/no_result.png" alt="" height="16" /></div>';

						echo $output;
					}
					else
						echo 0;
				break;
				case 8:
					if($_GET['manufacturer_id'])
					{
						$parameters_models = array('languageId'=>$languageId,'manufacturerId'=>$_GET['manufacturer_id'],'pc'=>1,'cv'=>0,'modelFilter'=>1);
						$result_models = $client->searchVehicleModelSeries($parameters_models);

						if(count($result_models))
						{
// 							$output = '<meta http-equiv="content-type" content="text/html; charset=Windows-1251" />
// 								   <link rel="stylesheet" type="text/css" href="css/styles.css" />
// 								   <div style="margin-bottom: 5px; font-size: 14px; font-weight: bold;">'.$_SESSION['manufacturers'][$_GET['manufacturer_id']].'</div>
// 								   <div class="car_manufacturer"><img src="images/bql_lek_avtomobil.png" alt="" height="20" /></div>';

							if( isset($_SERVER['HTTPS'] )  && $_SERVER['HTTPS'] != 'off' ) 
							    $redirect_path = 'https://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
							else
							    $redirect_path = 'http://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);

							$output = '<meta http-equiv="content-type" content="text/html; charset=Windows-1251" />
								   <link rel="stylesheet" type="text/css" href="css/styles.css" />
								   <div style="float:left; width: 100%; margin-bottom: 5px; font-size: 14px; font-weight: bold;">
									  <div id="leki_avtomobili" style="float: left; width: 123px; height: 15px;" onClick=\'window.location.href = "'.$redirect_path.'";\' onmouseover=\'this.style.cursor="pointer";\' onmouseout=\'this.style.cursor="normal";\'"></div>
									  <div style="float: left;">&nbsp;>>&nbsp;</div>
									  <div style="float: left;">'.$_SESSION['manufacturers'][$_GET['manufacturer_id']].'</div>
								   </div>';

							if(strlen($_GET['year'])==1)
								$titleYearManufactured = '200'.$_GET['year'];
							else
								$titleYearManufactured = '19'.$_GET['year'];

							$output.= '<div style="float: left; font-size: 13px; font-weight: bold; margin-top:10px; margin-bottom: 10px;">
									<img src="images/godina_na_proizvodstvo.png" alt="" height="16" style="float: left;" />
									<div style="float: left; margin-left: 10px; margin-right:5px;">'.$titleYearManufactured.' - </div>
									<a onmouseover="mouseOver(this);" onmouseout="mouseOut(this);" onClick="ajaxManufacturerLoadModels(7, '.$_GET['manufacturer_id'].')" style="float: left; color: #000000; text-decoration: underline; padding-right: 10px;">
										<div id="nov_izbor" style="float: left; margin-right: 10px;"></div>
									</a>
								   </div>
								   <div class="car_manufacturer" style="float: left;">
									<div class="car_manufacturer_left">
										<div style="float: left;"><img src="images/modelna_poredica.png" alt="" /></div>
										<div style="float: right;"><img src="images/bql_godina_na_proizvodstvo.png" alt="" /></div>
									</div>
									<div class="car_manufacturer_right">
										<div style="float: left;"><img src="images/modelna_poredica.png" alt="" /></div>
										<div style="float: right;"><img src="images/bql_godina_na_proizvodstvo.png" alt="" /></div>
									</div>
								   </div>';
							
							$isFlag = 0;
							foreach($result_models->modelSeries as $key=>$data)
							{
								$id = trim($data->id);
								$name = trim($data->name);

								if($id && $name!='')
								{
									$isFlag = 1;
									$flagManufacturedFrom = 0;
									$flagManufacturedTo = 0;

									if(isset($data->manufacturedFrom)){
										$manufacturedExpFrom = explode('.', $data->manufacturedFrom);

										$manufacturedFromYear = intval($manufacturedExpFrom[1]);
										$manufacturedFromSelYear = intval(((count($_GET['year'])==1) ? '0'.$_GET['year'] : $_GET['year']));

										if($manufacturedFromYear==$manufacturedFromSelYear)
											$flagManufacturedFrom = 1;
									}

									if(isset($data->manufacturedTo)){
										$manufacturedExpTo = explode('.', $data->manufacturedTo);
										$manufacturedToYear = intval($manufacturedExpTo[1]);
										$manufacturedToSelYear = intval(((count($_GET['year'])==1) ? '0'.$_GET['year'] : $_GET['year']));

										if($manufacturedToYear==$manufacturedToSelYear)
											$flagManufacturedTo = 1;

										$manufacturedFromTo = $data->manufacturedFrom.' - '.$data->manufacturedTo;
									}
									else
										$manufacturedFromTo = $data->manufacturedFrom;

									$i = 0;
									if($flagManufacturedFrom || $flagManufacturedTo) {
										$i++;

										if($i % 2 ==0){
											$output.= '<div class="car_manufacturer_right" id="table_manufacturer['.$data->id.']">
													<a onmouseover="mouseOver(this);" onmouseout="mouseOut(this);" onClick="this.style.color=\'#ff0000\'; ajaxShowResults(2, '.$_GET['manufacturer_id'].','.$data->id.', 0);">
														<span style="font-weight: bold;">'.mb_convert_encoding($data->name,'Windows-1251','UTF-8').'</span>
													</a>
													<div style="float: right;"><b>'.$manufacturedFromTo.'</b></div>
												    </div>';
										}
										else{
											$output.= '<div class="car_manufacturer_left" id="table_manufacturer['.$data->id.']" style="margin-right: 0.5%;">
													<a onmouseover="mouseOver(this);" onmouseout="mouseOut(this);" onClick="this.style.color=\'#ff0000\'; ajaxShowResults(2, '.$_GET['manufacturer_id'].', '.$data->id.', 0);">
														<span style="font-weight: bold;">'.mb_convert_encoding($data->name,'Windows-1251','UTF-8').'</span>
													</a>
													<div style="float: right;"><b>'.$manufacturedFromTo.'</b></div>
												   </div>';
										}
									}
								}
							}

							if(empty($isFlag))
								$output.= '<div class="no_result"><img src="images/no_result.png" alt="" height="16" /></div>';

							echo $output;
						}
						else
							echo $output.= '<div class="no_result"><img src="images/no_result.png" alt="" height="16" /></div>';
					}
					else
						echo 0;
				break;
				
				case 9:
					include('checkLogin.php');
				break;
		}

	}
?>
